package member.controller;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import member.model.MemberService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import to.DriverTO;
import to.MemberTO;
import driver.model.DriverService;

@Controller
public class MemberController {
	private DriverService dService;
	private MemberService mService;
	public MemberController(DriverService dService, MemberService mService){
		this.dService = dService;
		this.mService = mService;
	}
	//controller 메소드들
	//회원가입
	@RequestMapping("/member.do")
	public ModelAndView joinMember(HttpSession session, Map<String,String> map, MemberTO mto, DriverTO dto, String memberType){
		try {
			if(dto.getCarRegNum() != null && dto.getDlLicenseNum() != null){
				dService.joinDriver(dto);
			}
			if(mService.getMemberByPhone(mto.getPhone()) == null){
				String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
				String id = "";
				for(int i = 0; i < 5;i++){
					id = id + alphabet[(int)(Math.random()*26)];
				}
				id = id + System.currentTimeMillis();
				mto.setMemberId(id);
				mto.setMemberType(0);
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Calendar calendar = Calendar.getInstance();
				mto.setJoinDate(dateFormat.format(calendar.getTime()));
				mService.joinMember(mto);
				map.put("result", "가입을 축하드립니다.");
				session.setAttribute("login_info", mto);
			}else{
				map.put("result", "가입되어 있는 번호입니다.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			map.put("result", "에러가 발생하였습니다.");
		}
		return new ModelAndView("jsonview",map);
	}
	
	@RequestMapping("/joinPage.do")
	public String joinPage(){
		return "member/join_form.tiles";
	}
	
	@RequestMapping("/goModifyForm.do")
	public String goModifyForm(){
		return "member/top/member/modify_form.tiles";
	}
	
	@RequestMapping("/memberManage.do")
	public String memberManage(){
		return "member/login_success.tiles";
	}
	//login 처리
	@RequestMapping("/login.do")
	public ModelAndView login(Map<String,String> map, HttpServletRequest request, HttpServletResponse response, MemberTO mtoParam){
		MemberTO mto = null;
		try{
			if(mtoParam.getMemberId() == null){
				mto = mService.getMemberByPhone(mtoParam.getPhone());
			}else{
				mto = mService.getMemberById(mtoParam.getMemberId());
			}
			if(mto!=null){
				//패스 워드 비교
				if(mtoParam.getPassword().equals(mto.getPassword())){//ID/Password 모두 맞는 경우
					if(mto.getApproved() != 1){
						mto.setMemberType(0);
					}
					HttpSession session = request.getSession();
					session.setAttribute("login_info", mto);
					map.put("result", "로그인 성공");
				}else{//패스워드가 틀린 경우
					map.put("result", "패스워드가 틀렸습니다. 확인 후 다시 로그인 하세요.");
				}
			}else{//id가 없는 경우
				if(mtoParam.getMemberId() == null){
					map.put("result", mtoParam.getPhone() +"은 없는 번호입니다.");
				}else{
					map.put("result", mtoParam.getMemberId()+"은 없는 아이디입니다.");
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			map.put("result", "로그인 도중 오류 발생 : "+e.getMessage());
		}
		return new ModelAndView("jsonview",map);
	}
	
	//logout 처리
	@RequestMapping("/logout.do")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		
		MemberTO mto = (MemberTO)session.getAttribute("login_info");
		ModelAndView mv = new ModelAndView("/index.tiles");
		if(mto==null){
			mv.addObject("error_message", "로그인 후 로그아웃 할 수 있습니다. 로그아웃 먼저 하세요");
		}else{
			session.invalidate();
		}
		return mv;
	}
	
	//로그인 한 회원 정보 조회
	//로그인 여부만 체크 한 뒤 로그인 되어있으면 member_detail.jsp로 이동
	@RequestMapping("/info.do")
	public ModelAndView getLoginMemberInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ModelAndView mv = null;
		Object obj = session.getAttribute("login_info");
		if(obj==null){
			mv = new ModelAndView("member/login_form.tiles", "error_message", "로그인 후 회원정보 조회하십시요");
		}else{
			mv = new ModelAndView("member/top/member/member_detail.tiles");
		}
		return mv;
	}
	
	//회원 탈퇴 처리
	@RequestMapping("/remove.do")
	public ModelAndView removeMember(HttpServletRequest request, HttpServletResponse response, HttpSession session,DriverTO dto, MemberTO mto){
		MemberTO loginInfo = (MemberTO)session.getAttribute("login_info");
		ModelAndView mv = null;
		if(loginInfo == null){//로그인 안된 경우
			mv = new ModelAndView("member/login_form.tiles", "error_message", "로그인 후 탈퇴가 가능합니다. 로그인 먼저 하세요");
		}else{
			try {
				mService.removeMemberById(loginInfo.getMemberId());
				dService.removeDriverByPhone(loginInfo.getPhone());
				mv = new ModelAndView("index.tiles");
				//세션 소멸시키기
				session.invalidate();
			}catch (SQLException e) {
				e.printStackTrace();
				mv = new ModelAndView("member/error.tiles", "error_message", e.getMessage());
			}
		}
		return mv;
	}
	
	@RequestMapping("/allMember.do")
	//전체 회원 목록 조회
	public ModelAndView getMemberList(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = null;
		try {
			ArrayList<MemberTO> mList = mService.getMemberList();
			ArrayList<DriverTO> dList = dService.getDriverList();
			request.setAttribute("member_list", mList);
			request.setAttribute("driver_list", dList);
			mv = new ModelAndView("member/member_list.tiles");
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("member/error.tiles", "error_message", e.getMessage());
		}
		return mv;
	}

	//회원 정보 수정 폼 조회
	//로그인 여부만 체크후 로그인 되어있으면 modify_form.jsp로 이동
	@RequestMapping("/modify.do")
	public ModelAndView modifyForm(HttpServletRequest request, HttpServletResponse response, HttpSession session, MemberTO mto, String memberType){
		ModelAndView mv = null;
		Object obj = session.getAttribute("login_info");
		if(memberType.equals("관리자")){
			mto.setMemberType(1);
		}
		try {
			mService.modifyMember(mto);
			session.setAttribute("login_info", mto);
			mv = new ModelAndView("member/member_detail.tiles");
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("member/error.tiles", "error_message", e.getMessage());
		}
		if(obj==null){
			
		}else{
			mv = new ModelAndView("member/modify_form.tiles");
		}
		return mv;
	}
	
	//이름으로 검색
	@RequestMapping("/searchName.do")
	public ModelAndView searchMemberByName(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = null;
		//1. 요청파라미터 조회
		String name = request.getParameter("name");
		//2. B.L 처리
		try{
			ArrayList<MemberTO> list = mService.searchMemberByName(name);
			HashMap map = new HashMap();
			map.put("member_list", list);
			map.put("title", "이름으로 검색");
			map.put("search_value", name);
			mv = new ModelAndView("member/member_list.tiles", map);			
		}catch(SQLException sqle){
			sqle.printStackTrace();
			mv = new ModelAndView("member/error.tiles", "error_message", "이름으로 검색도중 오류발생 : "+sqle.getMessage());
		}	
		return mv;
	}		
}
